package com.swfcamp.shopper.amazon
{
	import com.swfcamp.shopper.IProductProvider;
	import com.swfcamp.shopper.ProductEvent;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.controls.HTML;

	[Event(name="com.swfcamp.shopper.ProductEvent:ProductFound", type="com.swfcamp.shopper.ProductEvent")]
	[Event(name="com.swfcamp.shopper.ProductEvent:ProductNotFound", type="com.swfcamp.shopper.ProductEvent")]
	
	public class AmazonProductProvider extends EventDispatcher implements IProductProvider 
	{
		
		protected var _apiKey:String;
		
		public function AmazonProductProvider(api:String)
		{
			_apiKey = api;	
		}

		public function search(query:String):ArrayCollection
		{
			return null;
		}
		
		public function detectProduct(html:HTML):void
		{
			var findDPAsin:RegExp = /\/dp\/(\w{10,10})/;
			var findGPAsin:RegExp = /\/gp\/product\/(\w{10,10})/;
			
			var evt:ProductEvent = null;
			
			var dpArray:Array = findDPAsin.exec(html.location);
			var gpArray:Array = findGPAsin.exec(html.location);
			
			var p:AmazonProduct;
			if( dpArray != null ){
				p = new AmazonProduct(dpArray[1],this);
				evt = new ProductEvent(ProductEvent.PRODUCT_FOUND,false,false,p);
			} else if( gpArray != null ){
				p = new AmazonProduct(gpArray[1],this);
				evt = new ProductEvent(ProductEvent.PRODUCT_FOUND,false,false,p);
			} else {
				evt = new ProductEvent(ProductEvent.PRODUCT_NOT_FOUND,false,false,null);
			}
			this.dispatchEvent(evt);
		}
		
		public function get apiKey():String{
			return _apiKey;
		}
		
		
	}
}